require 'nokogiri'
require 'open-uri'

class ForeignExchangeRate < ActiveRecord::Base
  
  belongs_to :money_type
  
#  validates_presence_of :spot_rate_buying_price,
#    :spot_cash_buying_price,
#    :selling_price,
#    :base_price,
#    :zh_convert_price
  validates_presence_of :released_at
  validates_uniqueness_of :money_type_id, :scope => :released_at
  
  def self.capture!
    doc = Nokogiri::HTML(open('http://www.boc.cn/sourcedb/whpj/index.html'))
    doc.css("table[@bgcolor='#EAEAEA'] tr[@align='center']").each do |tr|
      tds = tr.css('td')
      debug tds[0].content
      raise '解析不到汇率' if tds.length != 8
      ForeignExchangeRate.create :money_type => MoneyType.find_by_name!(tds[0].content),
        :spot_rate_buying_price => tds[1].content,
        :spot_cash_buying_price => tds[2].content,
        :selling_price => tds[3].content,
        :base_price => tds[4].content,
        :zh_convert_price => tds[5].content,
        :released_at => "#{tds[6].content} #{tds[7].content}"
    end
  end
  
  def spot_rate_buying_rate
    spot_rate_buying_price.present? ? format('%0.4f',(spot_rate_buying_price/100)) : nil
  end
  
  def spot_cash_buying_rate
    spot_cash_buying_price.present? ? format('%0.4f',(spot_cash_buying_price/100)) : nil
  end
  
  def selling_rate
    selling_price.present? ? format('%0.4f',(selling_price/100)) : nil
  end

  def self.debug  str
    puts str
    logger.debug str
  end
end
